<template>
  <el-row>
    <el-col class="el-col" :span="12" :offset="6">
      <header-com @add="add"></header-com>
      <hr />
      <list-com
        :todoList="todoList"
        :del="del"
        :changeFlag="changeFlag"
      ></list-com>
      <hr />
      <footer-com
        :all="todoList.length"
        :selectNum="selectNum"
        :allSelectIsOrNo="allSelectIsOrNo"
        :allSelectTodoList="allSelectTodoList"
        :selectAllDel="selectAllDel"
      ></footer-com>
    </el-col>
  </el-row>
  <is-xiang-ying></is-xiang-ying>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, watch, computed } from "vue";
import FooterCom from "./components/FooterCom.vue";
import HeaderCom from "./components/HeaderCom.vue";
import ListCom from "./components/ListCom.vue";
import IsXiangYing from "./components/IsXiangYing.vue";

import { todo } from "./types/todo";
export default defineComponent({
  components: { HeaderCom, ListCom, FooterCom, IsXiangYing },
  setup() {
    const todoList = reactive<todo[]>([
      {
        id: 0,
        title: "打篮球",
        flag: false,
      },
      {
        id: 1,
        title: "骑车",
        flag: false,
      },
      {
        id: 2,
        title: "下棋",
        flag: false,
      },
    ]);

    // 添加数据
    const add = (title: string) => {
      todoList.push({
        id: todoList.length,
        title,
        flag: false,
      });
    };

    const del = (index: number) => {
      todoList.splice(index, 1);
    };
    const changeFlag = (todo: todo, value: boolean) => {
      todo.flag = value;
      console.log(todoList);
    };

    const selectNum = ref<number>(0);
    watch(
      todoList,
      (value) => {
        console.log(value);
        selectNum.value = value.reduce((pre, item) => {
          return item.flag == true ? pre + 1 : pre;
        }, 0);
      },
      {
        deep: true,
        immediate: true,
      }
    );

    const allSelectIsOrNo = computed(() => {
      return selectNum.value == todoList.length ? true : false;
    });

    const allSelectTodoList = (value: boolean) => {
      todoList.forEach((item) => {
        item.flag = value;
      });
    };

    const selectAllDel = () => {
      const arr = todoList.filter((item) => {
        return item.flag == false;
      });
      todoList.length = 0;
      arr.forEach((item) => {
        todoList.push(item);
      });
    };

    return {
      todoList,
      add,
      del,
      changeFlag,
      selectNum,
      allSelectIsOrNo,
      allSelectTodoList,
      selectAllDel,
    };
  },
});
</script>

<style scoped>
.el-col {
  margin-top: 50px;
  border: 1px solid #ccc;
}
</style>